package com.link.base.core.baidu;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.link.base.core.basic.util.YmlConstants;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.HttpUtils;
import com.link.core.util.StringUtils;

import javax.validation.constraints.NotNull;

/**
 * 百度地图相关工具：根据gps坐标转换为地址。。。
 */
public class BaiDuMapUtil {

    private static final String REVERSE_GEO_URL = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=AK&output=json&coordtype=COORDTYPE&location=LOCATION";

    /**
     * 逆地理编码服务-将经纬度转换为地址
     * @param longitude 经度
     * @param latitude 纬度
     * @param coordtype  坐标类型 可以为空
     * @return  返回值示例 {"status":0,"result":{"location":{"lng":105.42736399999997,"lat":28.890862027308125},
     * "formatted_address":"四川省泸州市龙马潭区锦绣路","business":"锦绣,南光路,大通路",
     * "addressComponent":{"country":"中国","country_code":0,"country_code_iso":"CHN",
     * "country_code_iso2":"CN","province":"四川省","city":"泸州市","city_level":2,"district":"龙马潭区","town":"","town_code":"",
     * "adcode":"510504","street":"锦绣路","street_number":"","direction":"","distance":""},
     * "pois":[],"roads":[],"poiRegions":[],"sematic_description":"","cityCode":331}}
     */
    public static JsonObject reverseGeocoding(@NotNull Double longitude, @NotNull Double latitude, String coordtype) {
        if (longitude == null || latitude == null) {
            throw new BasicServiceException("经度或者纬度不能为空");
        }
        String location = latitude + "," + longitude;
        String baiduMapKey = YmlConstants.getBaiduMapKey();
        //如果没有传递 坐标类型，则设置为wgs84，企业微信小程序用的这个
        if (StringUtils.isBlank(coordtype)) {
            coordtype = "wgs84";
        }
        String url = REVERSE_GEO_URL.replace("AK", baiduMapKey).replace("COORDTYPE", coordtype).replace("LOCATION", location);
        String result = HttpUtils.sendPost(url, "");
        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
        int status = returnData.get("status").getAsInt();
        if (status == 0) {
            return returnData;
        } else {
            throw new BasicServiceException("请求数据发生错误，错误编码是：" + status + ";请根据错误编码查询具体错误，查询地址：http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad");
        }
    }
}
